package com.toommi.refuse.controller;

import com.alibaba.fastjson.JSONObject;
import com.toommi.refuse.common.response.CommonResponse;
import com.toommi.refuse.entity.WechatUserHousehold;
import com.toommi.refuse.exception.AppUserException;
import com.toommi.refuse.exception.WechatUserException;
import com.toommi.refuse.model.AppUserModel;
import com.toommi.refuse.model.WechatUserModel;
import com.toommi.refuse.service.WechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ..
 * 微信端用户操作
 *
 * @author yangg
 * @since 2019-07-24 17:38
 */
@RestController
@RequestMapping(value = "/api/wechat")
@Slf4j
@AllArgsConstructor
@Api(tags = "微信端用户管理操作")
public class WechatUserController {

    private WechatUserService wechatUserService;
    //公众号APPid
    private final  static String  gzappid="wxd8ce84192461a3fc";
    private final  static String  gzsecret="d7eac74151b2575622385192a953e75a";
    /**
     * 修改用户信息
     *
     * @param
     * @return 操作结果
     */
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息，用于完善个人信息")
    @ApiImplicitParam(name = "wechatUserModel", value = "用户信息实体", required = true, dataType = "WechatUserModel")
    @RequestMapping(value = "/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public CommonResponse addUser(String openid,String username,String phone,String code,HttpServletRequest request) {
        CommonResponse commonResponse = CommonResponse.success();
        String ip=request.getRemoteHost();
        String ip1=request.getRemoteAddr();
        log.info("ip==============="+ip1);
        if(!"183.69.212.176".equals(ip)){
            commonResponse = CommonResponse.forbidden();
            commonResponse.setMessage("内测中，无权限访问!");
            return commonResponse;
        }
        log.info("打印地址数据----------------"+ip+"-----------------"+ip1);
        try {
            commonResponse.setData(wechatUserService.updateUser(openid,username,phone,code));
        } catch (WechatUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("update wechat user error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }


    /**
     * 获取用户信息
     *
     * @param  userid
     * @return 操作结果
     */
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @RequestMapping(value = "/getuserinfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse getUserInfo(@RequestParam String userid) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(wechatUserService.getUserInfo(userid));
        } catch (Exception e) {
            log.error("get wechat user error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }


    /**
     * 获取用户二维码
     *
     * @param  openid
     * @return 操作结果
     */
    @ApiOperation(value = "获取用户二维码", notes = "获取用户二维码")
    @RequestMapping(value = "/getuserqrcode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse getUserQrcode(@RequestParam String openid) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(wechatUserService.getUserQrcode(openid));
        } catch (Exception e) {
            log.error("get wechat user error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }


    /**
     * 注册
     *
     * @param
     * @return 操作结果
     */
    @ApiOperation(value = "注册", notes = "注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public CommonResponse register(@RequestParam String phone,String password,String id,String name) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            wechatUserService.register(phone,password,id,name);
        } catch (Exception e) {
            log.error("get wechat user error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 回收端用户登录
     *
     * @param
     * @return 登录结果
     */
    @ApiOperation(value = "回收端用户登录", notes = "回收端用户登录")

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResponse login(String phone,String password) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(wechatUserService.login(phone,password));
        } catch (WechatUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("app user login error :{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 判断二维码是否正确
     *
     * @param  code
     * @return 操作结果
     */
    @ApiOperation(value = "判断二维码是否正确", notes = "判断二维码是否正确")
    @RequestMapping(value = "/judgeqrcode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse judgeQrcode(@RequestParam String code) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(wechatUserService.judgeQrcode(code));
//            if(num<=0){
//                commonResponse = CommonResponse.serverError();
//            }else{
//                commonResponse.setData("成功");
//            }

        } catch (Exception e) {
            log.error("get wechat user error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 用户绑定住址
     *
     * @param
     * @return 操作结果
     */
    @ApiOperation(value = "用户绑定地址", notes = "用户绑定地址")
    @ApiImplicitParam(name = "wechatUserHousehold", value = "用户/门牌号关联关系", required = true, dataType = "WechatUserHousehold")
    @RequestMapping(value = "/user/address", method = RequestMethod.POST)
    public CommonResponse bindAddress(@RequestBody WechatUserHousehold wechatUserHousehold) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            wechatUserService.bindAddress(wechatUserHousehold);
        } catch (WechatUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("bind wechat user address error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }


//    /**
//     * 微信判断我的钱包
//     *
//     * @return 操作结果
//     */
//    @ApiOperation(value = "微信判断我的钱包", notes = "微信判断我的钱包")
//    @RequestMapping(value = "/mymoney")
//    public void mymoney(HttpServletRequest request, HttpServletResponse response) {
//        try{
//            log.info("进入个人钱包跳转");
//            String code=request.getParameter("code");
//            if(StringUtils.isEmpty(code)){
//                log.info("跳转个人中心缺少code");
//            }
//            Map<String, String> params=new HashMap<String,String>();
//            String json=startAlipayGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+gzappid+"&secret="+gzsecret+"&code="+code+"&grant_type=authorization_code",params);
//            //解析json数据
//            JSONObject obejct=JSONObject.parseObject(json);
//            String openid=obejct.getString("openid");
//            Map<String,Object>user=wechatUserService.getUserInfoByOpenId(openid);
//            int is_ws=0;//未完善
//            String id=null;
//            if(user==null){
//            }else{
//              id= String.valueOf(user.get("id"));
//                if(user.get("address")==null){
//                    //这个时候是已经注册但是未完善
//                    is_ws=1;
//                }else{
//                    is_ws=2;//已完善
//                }
//            }
//            //获取到openid之后重定向到页面
//            response.sendRedirect("http://yugonghuanjing.com/Refuseclassification/index.html?openid="+openid+"&id="+id+"&is_ws="+is_ws);
//        }catch(Exception e){
//            log.info("小程序授权失败");
//
//        }
//    }
    /**
     * @seeget请求类
     */
    public String startAlipayGet(String url, Map<String, String> params) throws Exception {
        // Post请求的url，与get不同的是不需要带参数
        URL postUrl = new URL(url);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        // 设置是否向connection输出，因为这个是post请求，参数要放在
        // http正文内，因此需要设为true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // 默认是 GET方式
        connection.setRequestMethod("GET");
        // Post 请求不能使用缓存
        connection.setUseCaches(false);
        connection.setConnectTimeout(4000);
        connection.setReadTimeout(7000);
        // 设置本次连接是否自动重定向
        connection.setInstanceFollowRedirects(true);
        // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
        // 意思是正文是urlencoded编码过的form参数
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
        // 要注意的是connection.getOutputStream会隐含的进行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        // 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
//		String content = postParams(params);
        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
//		out.write(content.getBytes("UTF-8"));
        // 流用完记得关
//		out.flush();
//		out.close();
        // 获取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuffer result = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            result.append(line);
        }
        reader.close();
        // 该干的都干完了,记得把连接断了
        connection.disconnect();
        log.info("返回值-----------------" + result.toString());
        return result.toString();
    }
}
